let App = getApp();
Page({
  data: {
    title:"保养方案",
    packages: {},
    minusStatuses: [],
    status: 0,
    modalStatus: 0,
    newMiles: '',
    oldPrice: 0,
    saveMoney: 0,
    productNum: 0,
    isSetMeal: 0,
    setMealOriginalPrice: 0,
    setMealPrice: 0,
    discountType: 0,
    discountPerc: 0,
    saveAmount: 0
  },
  /**
   * 跳转车辆库（带参数）
   */
  jumpCarList() {
    wx.redirectTo({
      url: '../../car/list/index?type=1'
    })
  },
  // 打开弹窗
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  dig: function(e) {
    this.setData({
      modalName: null
    })
  },

  onLoad(options) {

    this.setData({
      options: options
    })

    let defaultCar = wx.getStorageSync('defaultCar')
    let miles = defaultCar.miles;

    let agent = wx.getStorageSync('agent')
    this.setData({
      agent,
      defaultCar,
      miles
    })

    wx.showNavigationBarLoading()
    this.getList(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })

    App.HttpService.readed().then(res => {
      console.log(res)
      var neirong = res.data.data[0].content

      this.setData({
        neirong
      })
    })
  },


  getList(cb) { // 套餐详情

    let {
      agent,
      defaultCar
    } = this.data

    App.HttpService.mealInfo({
      carId: defaultCar.carId,
      sellerId: wx.getStorageSync('agent').id,
      userId: wx.getStorageSync('userId')

    }).then(res => {

      cb && cb()
      let data = res.data

      if (data.code == 200) {
        // 优惠券显示隐藏
        wx.setStorageSync('isShareActivity', data.data.isShareActivity)
        data.data.info.forEach(item => {
          if (item.isReplace > 0) {
            item.selected = true
          } else {
            item.selected = false
          }
        })
        this.setData({
          hourFee: data.data.hourFee,

          packages: data.data.info,
          pack: data.data,
          isSetMeal: data.data.isSetMeal,
          setMealOriginalPrice: data.data.setMealOriginalPrice,
          setMealPrice: data.data.setMealPrice,
          discountType: data.data.discountType,
          discountPerc: data.data.discountPerc,
          fullInfo: data.data.fullInfo,

        })
        if (res.data.data.productHourFee) {
          this.setData({
            gonbgshifei: res.data.data.productHourFee
          })
        } else {
          this.setData({
            gonbgshifei: [],
          })
        }


        console.log(data.data.fullInfo)
        this.sum()
        let calSelected = this.calSelected();
        let productNum = calSelected.length;
        this.setData({
          productNum
        });
        let products = calSelected.map(item => {
          let product = {
            id: item.productId,
            name: item.productName,
            image: item.productImg,
            price: item.productTotal,
            oldPrice: item.productOriginalPrice,
            num: item.productNum,
            unit: item.productSpecification + item.productUnit,
            economies: item.productEconomies
          }
          return product
        });
        this.setData({
          productList: products
        });
        let oldPrice = 0;
        let saveMoney = 0;
        if (this.data.isSetMeal == 0) {
          for (let i = 0; i < products.length; i++) {
            oldPrice += products[i].oldPrice;
            saveMoney += products[i].economies;
          }
          saveMoney = saveMoney - this.data.saveAmount;
        } else {
          oldPrice = this.data.setMealOriginalPrice;
          saveMoney = this.data.setMealOriginalPrice - this.data.setMealPrice;
        }
        this.setData({
          oldPrice,
          saveMoney: saveMoney.toFixed(2)
        });
      }
    }, e => {
      cb && cb()
    })
  },
  toFixed() { // 保养手册
    wx.navigateTo({
      url: `/pages/repair/index`
    })
  },
  bindCheckbox(e) {

    /*绑定点击事件，将checkbox样式改变为选中与非选中*/
    let index = parseInt(e.currentTarget.dataset.index) //拿到下标值，以在carts作遍历指示用
    let packages = this.data.packages
    let selected = packages[index].selected //原始的icon状态
    if (packages[index].isReplace == 1) {
      packages[index].selected = true
      // packages.forEach(item => {
      //   if (item.isReplace) { // 更换分类绑定 同时选择或同时取消
      //     item.selected = packages[index].selected
      //   }
      // })
    } else {
      packages[index].selected = !selected // 对勾选状态取反
    }

    this.setData({
      packages
    })
    this.sum()
    let calSelected = this.calSelected();
    let productNum = calSelected.length;
    this.setData({
      productNum
    });
    let products = calSelected.map(item => {
      let product = {
        id: item.productId,
        name: item.productName,
        image: item.productImg,
        price: item.productTotal,
        oldPrice: item.productOriginalPrice,
        num: item.productNum,
        unit: item.productSpecification + item.productUnit,
        economies: item.productEconomies
      }
      return product
    });
    this.setData({
      productList: products
    });
    let oldPrice = 0;
    let saveMoney = 0;
    if (this.data.isSetMeal == 0) {
      for (let i = 0; i < products.length; i++) {
        oldPrice += products[i].oldPrice;
        saveMoney += products[i].economies;
      }
      saveMoney = saveMoney - this.data.saveAmount;
    } else {
      oldPrice = this.data.setMealOriginalPrice;
      saveMoney = this.data.setMealOriginalPrice - this.data.setMealPrice;
    }
    this.setData({
      oldPrice,
      saveMoney: saveMoney.toFixed(2)
    });

    var o = this.data.temp
    var l = this.data.cash

    if (o == 0 && l == 0) {
      this.setData({
        zhan: false
      })
    } else {
      this.setData({
        zhan: true
      })
    }


  },
  bindRadio(e) { // 更换商品

    let {
      index
    } = e.currentTarget.dataset
    let {
      types,
      defaults,
      packages
    } = this.data
    let {
      typeList
    } = types
    packages[defaults.index].defaultList = typeList[index].meals
    packages[defaults.index].total = typeList[index].total
    // 修改
    packages[defaults.index].originalTotal = typeList[index].originalTotal


    packages[defaults.index].mealsId = typeList[index].mealsId
    // 修改原价省钱那部分
    packages[defaults.index].economies = typeList[index].economies
    packages[defaults.index].finalTotal = typeList[index].finalTotal




    this.setData({
      'types.typeList': typeList,
      packages,
      showModalStatus: false
    })
    if (packages[defaults.index].selected) { // 分类选中 更换商品计算总价
      this.sum()
    }

  },
  // 更换弹窗
  setModalStatus(e) {

    let {
      status,
      index
    } = e.currentTarget.dataset
    let {
      packages
    } = this.data
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (status == 1) {
      let typeList = packages[index].typeList
      let mealsId = packages[index].mealsId
      typeList.forEach(item => { // 设置默认

        if (item.mealsId == mealsId) {
          item.selected = true
        } else {
          item.selected = false
        }
      })
      let defaults = {
        index: index, // 获取分类索引
        mealsId: packages[index].mealsId
      }
      this.setData({
        showModalStatus: true,
        defaults,
        types: {
          typeList: typeList,
          typeName: packages[index].typeName
        }
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  // 购物车详情弹窗
  setModalStatus2(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = !this.data.status;
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 1) {
      this.setData({
        showModalStatus2: true
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },
  // 隐藏购物车弹窗
  setModalStatus3(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = 0;
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 0) {
      this.setData({
        showModalStatus2: false
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },
  // 显示修改里程数
  editMileage() {
    this.setData({
      modalStatus: 1
    });
  },
  // 隐藏修改里程数
  hideModal() {
    this.setData({
      modalStatus: 0
    });
  },
  // 修改里程数
  bindInput(e) {
    this.setData({
      newMiles: e.detail.value
    });
  },
  // 确定修改里程数
  confirmEdit() {
    let mileage = this.data.newMiles;
    if (!this.data.miles) {
      this.setData({
        modalStatus: 0
      });
      return false;
    } else {
      if (mileage == '') {
        wx.showToast({
          title: '请输入里程',
          image: '../../../assets/images/warning.png'
        })
        return false;
      }
      let id = this.data.defaultCar.carId;

      App.HttpService.updateMileage({
        id,
        mileage
      }).then(res => {
        if (res.data.code == 200) {
          //修改成功后，更新本地默认车辆信息
          wx.getStorage({
            key: 'defaultCar',
            success: function(res) {
              res.data.miles = mileage;
              wx.setStorage({
                key: 'defaultCar',
                data: res.data,
              })
            },
          })
          this.getList();
        }
      });
      this.setData({
        miles: this.data.newMiles,
        modalStatus: 0
      });
    }
  },
  toMerchants() { // 去选店
    let calSelected = this.calSelected()
    if (calSelected.length <= 0) {
      wx.showToast({
        title: '请勾选商品',
        image: '../../../assets/images/warning.png',
        duration: 1000
      })
      return
    }
    let products = calSelected.map(item => {
      let product = {
        id: item.productId,
        name: item.productName,
        image: item.productImg,
        price: item.productTotal,
        oldPrice: item.productOriginalPrice,
        num: item.productNum,
        unit: item.productSpecification + item.productUnit,
        economies: item.productEconomies
      }
      console.log(product)
      return product
    })
    console.log(products);
    wx.setStorageSync('products', products)
    var k = this.data.total
    var kl = this.data.oldPrice
    wx.setStorageSync('qian', k)
    wx.setStorageSync('yuanjia', kl)
    var can = this.data.options.can
    var gsfid = JSON.stringify(this.data.gonbgshifei)


    var dateTime = new Date();
    var Time = new Date("January 12,2006 09:00:00");
    var time = Time.toLocaleTimeString();
    var mytime = dateTime.toLocaleTimeString();
    if (mytime > time) {

      var sj = 1
    } else {
      var sj = 0
    }
    wx.navigateTo({
      url: '/pages/merchants/list/index?productStatus=0' + "&can=" + can + "&gfid=" + gsfid + "&sj=" + sj
    })
  },
  toProduct(e) { // 商品详情
    let {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/product/detail/detail?id=${id}&package=1`
    })

  },
  calSelected() { // 遍历取出已勾选的cid
    let calSelected = []
    let packages = this.data.packages
    packages.forEach(item => {
      if (item.selected) {
        calSelected = [...calSelected, ...item.defaultList]
      }
    })
    return calSelected
  },
  sum() {
    // 计算总金额
    let packages = this.data.packages;
    let total = 0
    let saveAmount = 0
    if (this.data.isSetMeal == 0) {
      packages.forEach(item => {
        if (item.selected) {
          total += item.total
        }
      })
      // discountType == 1 大客户百分比
      if (this.data.discountType == 1) {
        saveAmount = total * this.data.discountPerc;
        total = total - saveAmount;
      }
      // 固定金额减免
      if (this.data.discountType == 2) {
        saveAmount = this.data.discountPerc;
        total = total - this.data.discountPerc;
      }
      total = total.toFixed(2)
    } else {
      total = this.data.setMealPrice;
    }




    var fullcuts = this.data.fullInfo
    let cash = 0;
    let temp = 0;
    fullcuts.forEach(item => {
      if (item.meet <= total) {
        if (item.meet >= temp) {
          temp = item.meet;
          cash = item.cash;
        }
      }
      this.setData({
        temp,
        cash
      })
    });
    if (this.data.gonbgshifei.status == 1) {
      var gsf = this.data.gonbgshifei.money
    } else {
      var gsf = 0
    }

    this.setData({
      packages,
      total: total - cash + gsf,
      saveAmount: saveAmount
    })


    let s = this.data.total
    if (s < 0) {
      this.setData({
        total: 0
      })


    }

  },
})